package com.backflash.server;

import java.util.Vector;

import javax.servlet.http.HttpSession;

import com.backflash.client.BackFlashService;
import com.backflash.client.Message;
import com.backflash.client.Topic;
import com.backflash.client.bean.User;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class BackFlashServiceImpl extends RemoteServiceServlet implements BackFlashService {

	DbHandler db = null;

	private static final String USER_SESSION = "GWTAppUser";
	private static final long serialVersionUID = 1;

	public void setUserInSession(User user){
		HttpSession session = getThreadLocalRequest().getSession();
		session.setAttribute(USER_SESSION, user);
	}
	
	public User getUserFromSession(){
		HttpSession session = getThreadLocalRequest().getSession();
		return (User) session.getAttribute(USER_SESSION);
	}
	
	public User checkLogin(String userName, String password){
		
		if(db == null) db = new DbHandler();
		
		Boolean loginOK = db.checkLogin(userName, password);
		
		if(loginOK){
			User user = new User();
			user.setUserName(userName);
			setUserInSession(user);
			return user;
		}
		else
		{
			return null;
		}
	}
	
	public Vector<String> getAllTopics(){

		if(db == null) db = new DbHandler();
		return db.getAllTopics();
	}
	
	public Topic getTopic(String topicHeading){
		if(db == null) db = new DbHandler();

		return db.getTopic(topicHeading); 
	}
	
	public void saveTopic(Topic t){
		
		if(db == null) db = new DbHandler();
		
		db.saveTopic(t);
	}
	
	public void saveMessage(Integer topicID, Message m){
		
		if(db == null) db = new DbHandler();
		
		db.saveMessage(topicID, m);
	}
	
	public void deleteTopic(String topicHeading){
		
		if(db == null) db = new DbHandler();
		
		db.deleteTopic(topicHeading);
	}
	
	public void deleteMessage(Integer topicID, Message m){
		
		if(db == null) db = new DbHandler();

		db.deleteMessage(topicID, m);
	}
	
	public Vector<User> getAllUsers(){
		
		if(db == null) db = new DbHandler();
		
		return db.getAllUsers();
	}
	
	public void deleteUser(String username){
		
		if(db == null) db = new DbHandler();
		
		db.deleteUser(username);
	}
	
	public void changeUserName(String oldUserName, String newUserName){
		
		if(db == null) db = new DbHandler();
		
		db.changeUserName(oldUserName, newUserName);
	}

}